package com.company.cloud.work.modules.app.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.auth.annotation.Login;
import com.company.cloud.common.bean.BaseClientResult;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant;
import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.common.utils.StrSplitUtils;
import com.company.cloud.user.modules.api.response.UserSimple;
import com.company.cloud.user.modules.api.service.UserRemoteService;
import com.company.cloud.work.modules.base.entity.WorkScheduleInfo;
import com.company.cloud.work.modules.base.service.WorkScheduleInfoService;
import com.company.cloud.work.modules.cache.models.WorkScheduleModel;
import com.company.cloud.work.modules.cache.utils.CrmWorkChangeUtils;
import com.company.cloud.work.modules.mgr.controller.req.WorkScheduleQuery4PageParam;
import com.company.cloud.work.modules.mgr.controller.req.WorkScheduleSaveParam;
import com.company.cloud.work.modules.mgr.controller.req.WorkScheduleUpdateParam;
import com.company.cloud.work.modules.mgr.service.WorkReceiptMgrService;
import com.company.common.server.constant.IRelBusiType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;


@Login
@RestController
@RequestMapping("/app/crm/workSchedule")
@Api(tags="CRM_APP_日程服务")
public class WorkScheduleAppController {

    @Autowired
    private WorkScheduleInfoService workScheduleInfoService;
    @Autowired
    private UserRemoteService userRemoteService;
    @Autowired
    private WorkReceiptMgrService workReceiptMgrService;


    @PostMapping("/query")
    @ApiOperation(value="查询", response=WorkScheduleModel.class)
    public BaseResult query(@RequestBody WorkScheduleQuery4PageParam params) {
        LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
        params.setUserId(userInfo.getId());
        String joinUserId=null;
        if(CheckUtils.hasInt(params.getJoinUserId())) {
            joinUserId= StrUtil.format(",{},", params.getJoinUserId());
        }
        IPage<WorkScheduleInfo> page =  workScheduleInfoService.page(
                new Page<>(params.getPage(), params.getRows()),
                new QueryWrapper<WorkScheduleInfo>()
                        .eq("rows_state", BaseConstant.EnabledEnum.ENABLED.getCode())
                        .eq(CheckUtils.hasInt(params.getUserId()), "user_id", params.getUserId())
                        .eq(StringUtils.hasText(params.getIsWholeDay()), "is_whole_day", params.getIsWholeDay())
                        .eq(StringUtils.hasText(params.getRelBizType()), "rel_biz_type", params.getRelBizType())
                        .eq(StringUtils.hasText(params.getRelBizId()), "rel_biz_id", params.getRelBizId())
                        .eq(StringUtils.hasText(params.getIsReceipt()), "is_repeat", params.getIsReceipt())
                        .like(StringUtils.hasText(joinUserId), "join_user_ids", joinUserId)
                        .apply(StringUtils.hasText(params.getDate()),"str_to_date({0},'%Y-%m-%d') >= str_to_date(start_date,'%Y-%m-%d')",params.getDate())
                        .apply(StringUtils.hasText(params.getDate()),"str_to_date({0},'%Y-%m-%d') <= str_to_date(end_date,'%Y-%m-%d')",params.getDate())
//				 .ge(condition, column, val)
        );

        if (page == null || CollectionUtils.isEmpty(page.getRecords())) {
            return BaseResult.ok();
        }
        Set<Integer> userIds=new HashSet<Integer>();
        page.getRecords().forEach(item->{
            if(CheckUtils.hasInt(item.getUserId())) {
                userIds.add(item.getUserId());
            }
            userIds.addAll(StrSplitUtils.parse2list(item.getJoinUserIds(), Integer.class));
        });
        BaseClientResult<Map<Integer, UserSimple>> userMap=userRemoteService.getUserMapByIds(userIds);

        IPage<WorkScheduleModel> data=page.convert(new Function<WorkScheduleInfo, WorkScheduleModel>() {
            @Override
            public WorkScheduleModel apply(WorkScheduleInfo entity) {
                if(CheckUtils.hasClientResult(userMap)){
                    return CrmWorkChangeUtils.getWorkScheduleModel(entity,userMap.getData());
                }else{
                    return CrmWorkChangeUtils.getWorkScheduleModel(entity,null);
                }
            }
        });
        return BaseResult.ok(data);
    }

    @PostMapping("/add")
    @ApiOperation(value="新增", response=BaseResult.class)
    public BaseResult add(@RequestBody WorkScheduleSaveParam params) {
        ValidatorUtils.validate(params);
        LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
        if(CollectionUtils.isEmpty(params.getJoinUserIds())){
            Set<Integer> joinUserIds=new HashSet<Integer>();
            joinUserIds.add(userInfo.getId());
            params.setJoinUserIds(joinUserIds);
        }
        WorkScheduleInfo entity=new WorkScheduleInfo();
        entity.setCompanyNo(userInfo.getCompanyNo());
        entity.setUserId(userInfo.getId());
        entity.setTitle(params.getTitle());
        entity.setContent(params.getContent());
        entity.setJoinUserIds(StrSplitUtils.list2string(params.getJoinUserIds()));
        entity.setIsWholeDay(params.getIsWholeDay());
        entity.setStartDate(params.getStartDate());
        entity.setEndDate(params.getEndDate());
        entity.setRemindDates(StrSplitUtils.list2string(params.getRemindDates()));
        entity.setRelBizType(params.getRelBizType());
        entity.setRelBizId(params.getRelBizId());
        entity.setIsReceipt(params.getIsReceipt());
        entity.addCreateParam(userInfo);
        entity.addEditParam(userInfo);
        workScheduleInfoService.save(entity);
        return BaseResult.ok();
    }


    @PostMapping("/edit")
    @ApiOperation(value="修改", response=BaseResult.class)
    public BaseResult edit(@RequestBody WorkScheduleUpdateParam params) {
        ValidatorUtils.validate(params);
        WorkScheduleInfo entity=workScheduleInfoService.getById(params.getId());
        if (entity == null || BaseConstant.EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
        entity.setTitle(params.getTitle());
        entity.setContent(params.getContent());
        entity.setJoinUserIds(StrSplitUtils.list2string(params.getJoinUserIds()));
        entity.setIsWholeDay(params.getIsWholeDay());
        entity.setStartDate(params.getStartDate());
        entity.setEndDate(params.getEndDate());
        entity.setRemindDates(StrSplitUtils.list2string(params.getRemindDates()));
        entity.setRelBizType(params.getRelBizType());
        entity.setRelBizId(params.getRelBizId());
        entity.setIsReceipt(params.getIsReceipt());
        entity.addEditParam(userInfo);
        workScheduleInfoService.updateById(entity);
        return BaseResult.ok();
    }

    @GetMapping("/get")
    @ApiOperation(value="获取", response=WorkScheduleModel.class)
    public BaseResult get(@RequestParam("id")Integer id) {
        WorkScheduleInfo entity=workScheduleInfoService.getById(id);
        if (entity == null || BaseConstant.EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();

        Set<Integer> userIds=new HashSet<Integer>();
        if(CheckUtils.hasInt(entity.getUserId())) {
            userIds.add(entity.getUserId());
        }
        userIds.addAll(StrSplitUtils.parse2list(entity.getJoinUserIds(), Integer.class));
        BaseClientResult<Map<Integer, UserSimple>> userMap=userRemoteService.getUserMapByIds(userIds);
        WorkScheduleModel data;
        if(CheckUtils.hasClientResult(userMap)){
             data= CrmWorkChangeUtils.getWorkScheduleModel(entity,userMap.getData());
        }else{
            data= CrmWorkChangeUtils.getWorkScheduleModel(entity,null);
        }
        if(BaseConstant.YNEnum.YES.getCode().equals(entity.getIsReceipt())) {
            workReceiptMgrService.save(IRelBusiType.CRM_Work_Schedule_ID, entity.getId().toString(), null, userInfo);
        }
        return BaseResult.ok(data);
    }


    @GetMapping("/remove")
    @ApiOperation(value="删除", response=BaseResult.class)
    public BaseResult remove(@RequestParam("id")Integer id) {
        WorkScheduleInfo entity=workScheduleInfoService.getById(id);
        if (entity == null || BaseConstant.EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
        entity.setRowsState(BaseConstant.EnabledEnum.DISABLED.getCode());
        entity.addEditParam(userInfo);
        workScheduleInfoService.updateById(entity);
        return BaseResult.ok();
    }


}
